package com.yoo.ons.function.home

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.view.animation.Interpolator
import android.view.animation.LinearInterpolator
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.yoo.module_base.dialog.CustomPopup
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.log
import com.yoo.module_base.view.index.slideview.IndexSlideCardAbleMethod
import com.yoo.module_base.view.index.slideview.IndexSlideCardAnimSetting
import com.yoo.module_base.view.index.slideview.IndexSlideCardDirection
import com.yoo.module_base.view.index.slideview.IndexSlideCardDuration
import com.yoo.module_base.view.index.slideview.IndexSlideCardLayoutManager
import com.yoo.module_base.view.index.slideview.IndexSlideCardListener
import com.yoo.ons.R
import com.yoo.ons.base.BaseVMFragment
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.base.adpater.isRefreshing
import com.yoo.ons.databinding.FragmentHomeBinding
import com.yoo.ons.dialog.ProfileInfoDialogFragment
import com.yoo.ons.event.MessageEvent
import com.yoo.ons.function.MainViewModel
import com.yoo.ons.function.home.viewmodel.HomeViewModel
import com.yoo.ons.function.like.MatchSuccessDialogFragment
import com.yoo.ons.listener.OnSwipeTouchListener
import com.yoo.ons.model.HomeListModel
import com.yoo.ons.util.Injections.mainHandler
import com.yoo.ons.util.appContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


const val HOME_CARD_UNLIKE_CLICK = "HOME_CARD_UNLIKE_CLICK"//点击不喜欢
const val HOME_CARD_LIKE_CLICK = "HOME_CARD_LIKE_CLICK"//点击喜欢
const val HOME_CARD_NICKNAME_CLICK = "HOME_CARD_NICKNAME_CLICK"//点击昵称
const val HOME_CARD_FLASH_CHAT_CLICK = "HOME_CARD_FLASH_CHAT_CLICK"//点击fc
const val HOME_CARD_ERROR_TRY_AGAIN_CLICK = "HOME_CARD_ERROR_TRY_AGAIN_CLICK"//点击网络错误的try again

class HomeFragment : BaseVMFragment<FragmentHomeBinding, HomeViewModel>(
    FragmentHomeBinding::inflate,
    HomeViewModel::class.java
), IndexSlideCardListener {
    private val mainViewModel by lazy {
        ViewModelProvider(requireActivity())[MainViewModel::class.java]
    }
    private val adapter by lazy { HomeDataListAdapter() }
    private val manager by lazy { activity?.let { IndexSlideCardLayoutManager(it, this) } }
    private val httpListener = object : HttpRequestListener<HomeListModel>() {
        override fun addRequestParams(params: HashMap<String, Any>) {
        }

        override fun success(t: HomeListModel?) {

        }
    }

    //保存点击和划卡喜欢和不喜欢的bean对象
    private var modelBean: HomeListModel.MatchIndexBean? = null

    //当点击昵称的时候获取viewHolder保存
    private var cardViewHolder: RecyclerView.ViewHolder? = null

    //保存当点击信息弹窗显示，然后点击弹窗里面的fc需要保存一些model信息
    private var nickName: String? = null
    private var friendUserCode: String? = null
    private var avatarUrl: String? = null

    override fun initData() {
        mViewModel?.setListener(httpListener)
        initialViews()
        dispatchRequest()
    }


    override fun initListener() {
    }

    private fun dispatchRequest() {
        mViewModel?.reqIndexList(true)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        manager?.removeAllViews()
    }

    private fun initialViews() {
        mViewModel?.clickFcLiveData?.observe(viewLifecycleOwner) {
            if (it) {
                //点击fc走like逻辑
                likeClick(modelBean)
            }
        }
        mViewModel?.dataAllList?.observe(viewLifecycleOwner) {
            adapter.submitList(it)
        }
        mViewModel?.loading?.observe(viewLifecycleOwner) {
            if (it.isRefreshing()) {
                binding?.listLoaderJson?.visibility = View.VISIBLE
            } else {
                //loading延迟消失
                mainHandler.postDelayed({
                    binding?.listLoaderJson?.visibility = View.GONE
                }, 500)
            }
        }
        mainViewModel.cardSlideState.observe(viewLifecycleOwner) {
            if (it) {
                cardViewHolder?.let {
                    adapter.hideCardContentUI(it, true)
                    mainViewModel.showMainTab(true)
                }
            }
            manager?.setCanScrollHorizontal(it)
        }
        mainViewModel.clickMenuType.observe(viewLifecycleOwner) {
            //监听来自弹窗里面按钮的点击事件类型
            when (it) {
                1 -> dislikeClick(null)
                2 -> likeClick(null)
                3 -> flashChatCLick(null)
            }
        }
        initCardConfig()
    }


    /**
     * 卡片初始化配置
     */
    private fun initCardConfig() {
        manager?.setVisibleCount(2)
        manager?.setTranslationInterval(4.0f)
        manager?.setScaleInterval(0.70f)
        manager?.setSwipeThreshold(0.6f)
        manager?.setMaxDegree(50.0f)
        manager?.setDirections(IndexSlideCardDirection.HORIZONTAL)
        manager?.setCanScrollHorizontal(true)
        manager?.setCanScrollVertical(false)
        manager?.setSwipeableMethod(IndexSlideCardAbleMethod.AutomaticAndManual)
        manager?.setOverlayInterpolator(LinearInterpolator())
        val direction = IndexSlideCardDirection.Left
        val duration = IndexSlideCardDuration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = IndexSlideCardAnimSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager?.setSwipeAnimationSetting(swipeAnimationSetting)
        binding?.homeSlideCardView?.layoutManager = manager
        binding?.homeSlideCardView?.adapter = adapter
        adapter.setListener(::handleAdapterListener)
        // 解决调用 notifyItemChanged 闪烁问题,取消默认动画
        (binding?.homeSlideCardView?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations =
            false
        binding?.homeSlideCardView?.itemAnimator.apply {
            if (this is DefaultItemAnimator) {
                supportsChangeAnimations = false
            }
        }

        // 添加自定义的触摸监听器
        binding?.homeSlideCardView?.let {
            it.addOnItemTouchListener(
                OnSwipeTouchListener(
                    appContext,
                    it
                ) { viewHolder, direction ->
                    when (direction) {
                        OnSwipeTouchListener.SwipeDirection.RIGHT -> {
                            // 处理向右滑动事件
                            manager?.setCanScrollHorizontal(true)
                            log("Swiped Right on item ${viewHolder.absoluteAdapterPosition}")
                        }

                        OnSwipeTouchListener.SwipeDirection.LEFT -> {
                            // 处理向左滑动事件
                            manager?.setCanScrollHorizontal(true)
                            log("Swiped Left on item ${viewHolder.absoluteAdapterPosition}")
                        }

                        OnSwipeTouchListener.SwipeDirection.UP -> {
                            // 处理向上滑动事件
                            manager?.setCanScrollHorizontal(false)
                            if (viewHolder is HomeDataListViewHolder) {
                                adapter.setBannerCurrentItem(viewHolder, 0)
                            }
                            log("Swiped Up on item ${viewHolder.absoluteAdapterPosition}")
                        }

                        OnSwipeTouchListener.SwipeDirection.DOWN -> {
                            // 处理向下滑动事件
                            manager?.setCanScrollHorizontal(false)
                            log("Swiped Down on item ${viewHolder.absoluteAdapterPosition}")
                            if (viewHolder is HomeDataListViewHolder) {
                                adapter.setBannerCurrentItem(viewHolder, 1)
                            }
                        }
                    }
                })
        }


    }

    private fun handleAdapterListener(action: String, item: Any?) {
        when (action) {
            HOME_CARD_UNLIKE_CLICK -> (item as? View)?.let(::dislikeClick)
            HOME_CARD_LIKE_CLICK -> ((item as? View)?.tag as? Pair<HomeListModel.MatchIndexBean, Int>)?.first?.let(
                ::likeClick
            )

            HOME_CARD_NICKNAME_CLICK -> (item as? View)?.let(::nicknameCLick)
            HOME_CARD_FLASH_CHAT_CLICK -> (item as? View)?.let(::flashChatCLick)
            HOME_CARD_ERROR_TRY_AGAIN_CLICK -> (item as? View)?.let(::tryAgainCLick)
        }
    }

    /**
     * 点击fc
     * */
    private fun flashChatCLick(itemView: View?) {
        if (itemView == null) {
            //是从信息弹窗里面点击fc
            showFcAnim(avatarUrl, friendUserCode, nickName)
        } else {
            //首页点击fc
            val bean = (itemView.tag as? Pair<HomeListModel.MatchIndexBean, Int>)?.first
            //val bean = it.tag as HomeListModel.MatchIndexBean
            showFcAnim(bean?.avatarUrl, bean?.friendUserCode, bean?.nickName)
        }
    }

    /**
     * 点击try again
     * */
    private fun tryAgainCLick(itemView: View?) {
        itemView?.let {
            mViewModel?.reqIndexList(true)
        }
    }

    private fun showFcAnim(avatarUrl: String?, friendUserCode: String?, nickName: String?) {
        if (binding?.imgHomeFlashChatAnim?.visibility == View.GONE) {
            // Load the fade-in animation
            val fadeInAnimation = AnimationUtils.loadAnimation(
                activity,
                com.yoo.module_res.R.anim.fade_in_flashchat
            )
            // Set the ImageView to be visible
            binding?.imgHomeFlashChatAnim?.visibility = View.VISIBLE
            fadeInAnimation.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(p0: Animation?) {
                }

                override fun onAnimationEnd(p0: Animation?) {
                    binding?.imgHomeFlashChatAnim?.visibility = View.GONE
                    FlashChatDialogFragment.newInstance(
                        avatarUrl ?: "",
                        friendUserCode ?: "",
                        nickName ?: ""
                    ).show(activity?.supportFragmentManager)
                }

                override fun onAnimationRepeat(p0: Animation?) {
                }
            })
            // Start the animation
            binding?.imgHomeFlashChatAnim?.startAnimation(fadeInAnimation)
        }
    }

    /**
     * 点击昵称
     * */
    private fun nicknameCLick(itemView: View?) {
        itemView?.let {
            val index = (itemView.tag as? Pair<HomeListModel.MatchIndexBean, Int>)?.second ?: 0
            //隐藏adapter里面显示的内容和按钮
            cardViewHolder =
                binding?.homeSlideCardView?.findViewHolderForAdapterPosition(index) ?: return
            adapter.hideCardContentUI(cardViewHolder!!, false)
            mainViewModel.showMainTab(false)
            //因为信息弹窗点击fc后需要走like逻辑、所以保存这个bean
            modelBean = (itemView.tag as? Pair<HomeListModel.MatchIndexBean, Int>)?.first
            //因为显示信息弹窗的fc，需要一些信息昵称、头像、code
            nickName = modelBean?.nickName
            friendUserCode = modelBean?.friendUserCode
            avatarUrl = modelBean?.avatarUrl

            //val bean = it.tag as HomeListModel.MatchIndexBean
            //设置卡片不可滑动
            mainViewModel.slideCardState(false)
            ProfileInfoDialogFragment.newInstance(modelBean?.friendUserCode ?: "", 0)
                .show(childFragmentManager, "ProfileInfoDialogFragment")
        }
    }

    /**
     * 喜欢的点击事件
     */
    private fun likeClick(bean: HomeListModel.MatchIndexBean?) {
        val direction = IndexSlideCardDirection.Right
        val duration = IndexSlideCardDuration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = IndexSlideCardAnimSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager?.setSwipeAnimationSetting(swipeAnimationSetting)
        binding?.homeSlideCardView?.swipe()
    }

    /**
     * 不喜欢的点击事件
     */
    private fun dislikeClick(itemView: View?) {
        itemView?.let {
            modelBean = (itemView.tag as? Pair<HomeListModel.MatchIndexBean, Int>)?.first
        }
        val direction = IndexSlideCardDirection.Left
        val duration = IndexSlideCardDuration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = IndexSlideCardAnimSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager?.setSwipeAnimationSetting(swipeAnimationSetting)
        binding?.homeSlideCardView?.swipe()
    }

    //划卡和点击喜欢不喜欢请求
    private fun postUserAddLike(direction: String) {
        modelBean?.let { model ->
            mViewModel?.postUserLike(direction, model.friendUserCode ?: "") { matchBean ->
                //得到划卡结果
                matchBean?.let {
                    if (direction == "Right" && it.matched) {
                        MatchSuccessDialogFragment.newInstance(
                            model.avatarUrl ?: "",
                            model.friendUserCode ?: ""
                        ).show(childFragmentManager)
                    }
                }
            }
        }
    }

    //卡片滑动（点击）监听
    override fun onCardDragging(direction: IndexSlideCardDirection?, ratio: Float) {
        //卡片滑动监听
        log("onCardDragging ${direction.toString()}")
    }

    override fun onCardSwiped(direction: IndexSlideCardDirection?) {
        //卡片滑动完成
        log("onCardSwiped")
        val position = manager?.topPosition ?: 0
        //1、划卡或者点击 喜欢，不喜欢2、在信息弹窗页面点击喜欢和不喜欢
        modelBean = adapter.getCardItem(position - 1)
        postUserAddLike(direction.toString())
        log("position=$position adapter.itemCount=${adapter.itemCount}  ${adapter.itemCount - 10}")
        if (position == adapter.itemCount - 10) {
            mViewModel?.reqIndexList(false)
        }
    }

    override fun onCardRewound() {
        //卡片回滚监听
        Log.i("HomeCard", "onCardRewound")
    }

    override fun onCardCanceled() {
        //卡片取消滑动监听
        log("onCardCanceled")
    }

    override fun onCardAppeared(view: View?, position: Int) {
        //卡片出现监听
        log("onCardAppeared")
    }

    override fun onCardDisappeared(view: View?, position: Int) {
        //卡片消失监听
        log("onCardDisappeared")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent?) {
        when (event?.type) {
            3 -> {
                log("card data is empty")
                //当划卡出现空，或者划完没有更多的时候，禁止这个划卡动作
                mainViewModel.slideCardState(false)
            }

            4 -> {
                mViewModel?.reqIndexList(true)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}

